import { useState, useEffect } from 'react';
import { Card, message, Typography, Divider, Space, Alert } from 'antd';
import { useNavigate, Link } from 'react-router-dom';
import { LoginOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import RegisterForm from '../../components/register/RegisterForm';
import authApi from '../../api/auth';
import { RegisterRequest } from '../../api/auth';
import './register.scss';

const { Title, Paragraph } = Typography;

const Register: React.FC = () => {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const navigate = useNavigate();
    const [bubbles, setBubbles] = useState<{ size: number; left: string; top: string; delay: number }[]>([]);

    // 在组件加载时检查是否已登录，如果已登录则重定向到欢迎页
    useEffect(() => {
        if (authApi.isAuthenticated()) {
            navigate('/welcome');
        }
    }, [navigate]);

    useEffect(() => {
        // 创建随机气泡装饰元素
        const newBubbles = Array(8).fill(0).map(() => ({
            size: Math.random() * 100 + 50,
            left: `${Math.random() * 100}%`,
            top: `${Math.random() * 100}%`,
            delay: Math.random() * 2
        }));
        setBubbles(newBubbles);
    }, []);

    const onFinish = async (values: RegisterRequest) => {
        setLoading(true);
        setError(null);

        try {
            // 调用API进行注册
            const response = await authApi.register(values);

            if (response.success && response.data) {
                message.success('注册成功！已自动登录');
                navigate('/welcome');
            } else {
                setError(response.message || '注册失败，请稍后重试');
                message.error(response.message || '注册失败');
            }
        } catch (error) {
            console.error('注册错误:', error);
            setError('服务器连接异常，请稍后重试');
            message.error('注册过程中发生错误，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    // 根据气泡尺寸获取对应的类名
    const getBubbleSizeClass = (size: number) => {
        if (size < 70) return 'background-bubble--size-1';
        if (size < 100) return 'background-bubble--size-2';
        if (size < 130) return 'background-bubble--size-3';
        return 'background-bubble--size-4';
    };

    // 根据延迟获取对应的类名
    const getBubbleDelayClass = (delay: number) => {
        if (delay < 0.5) return 'background-bubble--delay-1';
        if (delay < 1) return 'background-bubble--delay-2';
        if (delay < 1.5) return 'background-bubble--delay-3';
        return 'background-bubble--delay-4';
    };

    return (
        <div className="register-container">
            {/* 添加背景装饰气泡 */}
            {bubbles.map((bubble, index) => (
                <div
                    key={index}
                    className={`background-bubble ${getBubbleSizeClass(bubble.size)} ${getBubbleDelayClass(bubble.delay)}`}
                    style={{ left: bubble.left, top: bubble.top }}
                />
            ))}

            <Card className="register-card" bordered={false}>
                <div className="register-logo">
                    <img src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" alt="Logo" />
                </div>

                <div className="register-header">
                    <Title level={2}>创建新账号</Title>
                    <Paragraph>加入我们，开始企业管理之旅</Paragraph>
                </div>

                {error && (
                    <Alert
                        message="注册失败"
                        description={error}
                        type="error"
                        showIcon
                        closable
                        style={{ marginBottom: 20 }}
                        onClose={() => setError(null)}
                    />
                )}

                <RegisterForm onFinish={onFinish} loading={loading} />

                <div className="register-footer">
                    <Space split={<Divider type="vertical" />}>
                        <Link to="/login" className="login-link">
                            <LoginOutlined /> 返回登录
                        </Link>
                        <a href="#" className="help-link">
                            <QuestionCircleOutlined /> 帮助
                        </a>
                    </Space>
                    <p>© {new Date().getFullYear()} 企业管理系统</p>
                </div>
            </Card>
        </div>
    );
};

export default Register; 